<?php
/**
 * @author jan
 */
class ViParticipant_Controller extends AdminController {

    public function __construct() {
        parent::__construct('viSeminar');
        $this->setDefaultListOrder('id');
    }

    public function index() {
        return $this->exportByTagForm();
    }

    public function exportByTagForm() {
        $this->exportByTagData();
        $this->viewData['formData'] = array('present_only' => TRUE);
        $this->renderSubview('/admin/viParticipant/viParticipantReport');
    }

    private function exportByTagData() {
        // Read all used seminar tags
        $this->viewData['viSeminarTagOptions'] = $this->dao->queryOptions(
                'SELECT id, name FROM vi_seminar_tag tag ' .
                'WHERE id IN (SELECT id FROM vi_seminar_tag_asoc) ' .
                'ORDER BY name');
    }

    public function exportByTag() {
        $formData = $this->postToDbValues();
        $this->viewData['formData'] = $formData;
        
        if (! $formData['vi_seminar_tag_ids']) {
            $this->msg->error('viParticipant.error-chooseTags');
            $this->exportByTagData();
            $this->renderSubview('/admin/viParticipant/viParticipantReport');
            return;
        }

        foreach ($formData['vi_seminar_tag_ids'] as $tagId) {
            if (! valid::isId($tagId)) {
                $this->msg->error('error.invalidId');
                $this->exportByTagData();
                $this->renderSubview('/admin/viParticipant/viParticipantReport');
                return;
            }
        }
        $tagIdString = implode(',', $formData['vi_seminar_tag_ids']);

        $personList = $this->dao->queryAll(
                'SELECT p.last_name, p.first_name, p.email FROM person p ' .
                'WHERE p.id IN (' .
                'SELECT DISTINCT r.person_id ' .
                'FROM vi_registration r ' .
                'JOIN vi_seminar_tag_asoc t ON r.vi_seminar_id = t.vi_seminar_id ' .
                'WHERE r.person_id = p.id ' . ($formData['present_only'] ? 'AND r.is_present = true' : '') . ' AND t.vi_seminar_tag_id IN (' . $tagIdString . '))');

        if (count($personList) == 0) {
            $this->msg->warning('viParticipant.noPersonToExport');
            $this->exportByTagData();
            $this->renderSubview('/admin/viParticipant/viParticipantReport');
            return;
        }

        $tmpExcelFileName = excel::simpleReport($personList, array('last_name', 'first_name', 'email'));

        download::force($tmpExcelFileName, NULL, 'Účastníci.xlsx');
    }

}
